"""
    Contains Person class and accompanying classes.
"""

from sqlobject import DatabaseIndex, MultipleJoin
from sqlobject.col import UnicodeCol, ForeignKey, BoolCol
from mnemoply.model.model_object import ModelObject
from mnemoply.model.hub import __connection__

class Position(ModelObject):
    """
        Position for person. Simple dictionary.
    """

    model_title = _("Position")

    name = UnicodeCol(length=80, notNull=True, alternateID=True, title=_("Name"))
    comment = UnicodeCol(default='', notNull=True, title=_("Comment"))
    title = property(lambda self: self.name)

class PersonPosition(ModelObject):
    """
        m2m relation between persons and positions. Also contains additional info.
    """

    model_title = _("Person position")

    person = ForeignKey('Person', notNull=True, cascade=True, title=_("Person"))
    position = ForeignKey('Position', notNull=True, title=_("Position"))
    organization = ForeignKey('Organization', default=None, title=_("Organization"))
    busyness = ForeignKey('BusynessType', default=None, title=_("Busyness"))
    personPosition = DatabaseIndex('person', 'position', 'organization', unique=True)

    title = property(lambda self: "%s: %s" % (self.person.title, self.position.title))

class PersonPlan(ModelObject):
    """
        m2m relation between persons and plan.
        Actually only for teacher, but never checked.
    """

    model_title = _("Person plan")

    person = ForeignKey('Person', notNull=True, cascade=True, title=_("Person"))
    plan = ForeignKey('Plan', notNull=True, title=_("Plan"))
    personPlan = DatabaseIndex('person', 'plan', unique=True)

    title = property(lambda self: "%s: %s" % (self.person.title, self.plan.title))

class Person(ModelObject):
    """
        UCVT worker.
    """

    model_title = _("Person")

    surname = UnicodeCol(length=80, default='', notNull=True, title=_("Surname"))
    forename = UnicodeCol(length=80, default='', notNull=True, title=_("Forename"))
    patronymic = UnicodeCol(length=80, default='', notNull=True, title=_("Patronymic"))
    phone = UnicodeCol(length=100, default='', notNull=True, title=_("Phone"))
    email = UnicodeCol(length=140, default='', notNull=True, title=_("e-mail"))
    office = ForeignKey('Office', default=None, title=_("Office"))
    canTeach = BoolCol(notNull=True, default=0, title=_("Can teach?"))
    positions = MultipleJoin('PersonPosition')
    plans = MultipleJoin('PersonPlan')

    comment = UnicodeCol(default='', notNull=True, title=_("Comment"))

    def _io(self, s):
        s = s.strip()

        if not len(s):
            return ""
        else:
            return s[0] + "."

    title = property(lambda self: "%s %s%s" % \
        (self.surname, self._io(self.forename), self._io(self.patronymic)))

